package cn.springsoter.core.tool.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 
 * 统一处理request header头信息，并放到threadlocal变量中，供controller/service使用
 * 
 * @author kevin
 *
 */
public class ThreadLocalUtil {

	private static final ThreadLocal<Map<String, Object>> threadLocal = ThreadLocal.withInitial(() -> new HashMap<>(8));

	/**
	 * 获取Map
	 * 
	 * @return
	 */
	public static Map<String, Object> getThreadLocal() {
		return threadLocal.get();
	}

	/**
	 * 根据Key获取Value
	 * 
	 * @param key
	 * @return
	 */
	public static Object get(String key) {
		Map<String, Object> map = ThreadLocalUtil.getThreadLocal();
		return map.get(key);
	}

	/**
	 * 根据Key获取Value，如果没有值，则返回默认值defaultValue
	 * 
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static Object get(String key, Object defaultValue) {
		Map<String, Object> map = ThreadLocalUtil.getThreadLocal();
		return map.get(key) == null ? defaultValue : map.get(key);
	}

	/**
	 * 设置Key和Value到ThreadLocal
	 * 
	 * @param key
	 * @param value
	 */
	public static void set(String key, Object value) {
		Map<String, Object> map = ThreadLocalUtil.getThreadLocal();
		map.put(key, value);
	}

	/**
	 * 设置Map<String, Object>到ThreadLocal
	 * 
	 * @param keyValueMap
	 */
	public static void set(Map<String, Object> keyValueMap) {
		Map<String, Object> map = ThreadLocalUtil.getThreadLocal();
		map.putAll(keyValueMap);
	}

	/**
	 * 删除ThreadLocal里的对象
	 */
	public static void remove() {
		threadLocal.remove();
	}

	/**
	 * 根据Key前缀匹配所有符合的Map<String, Object>
	 * 
	 * @param keyPrefix
	 * @return
	 */
	public static Map<String, Object> fetchVarsByPrefix(String keyPrefix) {
		Map<String, Object> vars = new HashMap<>();
		if (keyPrefix == null) {
			return vars;
		}
		Map<String, Object> map = ThreadLocalUtil.getThreadLocal();
		Set<Map.Entry<String, Object>> set = map.entrySet();

		for (Map.Entry<String, Object> entry : set) {
			Object key = entry.getKey();
			if (key instanceof String) {
				if (((String) key).startsWith(keyPrefix)) {
					vars.put((String) key, entry.getValue());
				}
			}
		}
		return vars;
	}

	/**
	 * 根据Key删除值
	 * 
	 * @param key
	 * @return	被删除的Value
	 */
	public static Object remove(String key) {
		Map<String, Object> map = ThreadLocalUtil.getThreadLocal();
		return map.remove(key);
	}

	/**
	 * 根据Key前缀删除匹配的值
	 * 
	 * @param keyPrefix
	 */
	public static void clear(String keyPrefix) {
		if (keyPrefix == null) {
			return;
		}
		Map<String, Object> map = ThreadLocalUtil.getThreadLocal();
		Set<Map.Entry<String, Object>> set = map.entrySet();
		List<String> removeKeys = new ArrayList<>();

		for (Map.Entry<String, Object> entry : set) {
			Object key = entry.getKey();
			if (key instanceof String) {
				if (((String) key).startsWith(keyPrefix)) {
					removeKeys.add((String) key);
				}
			}
		}
		for (String key : removeKeys) {
			map.remove(key);
		}
	}

}
